<?php

namespace common\models\base;

use Yii;
use yii\db\Query;

class DatabaseManager
{
    public static function getDb()
    {
        return Yii::$app->get("db");
    }

    static function queryAll($sql, \yii\db\Connection $db = null)
    {
        $db = $db ? $db : \Yii::$app->db;
        $query = new Query();
        $data = $query->createCommand($db)->setSql($sql)->queryAll();
        return $data;
    }

    static function queryOne($sql, \yii\db\Connection $db = null)
    {
        $db = $db ? $db : \Yii::$app->db;
        $query = new Query();
        $data = $query->createCommand($db)->setSql($sql)->queryOne();
        return $data;
    }

    static function execute($sql, \yii\db\Connection $db = null)
    {
        $db = $db ? $db : \Yii::$app->db;
        $query = new Query();
        $flag = $query->createCommand($db)->setSql($sql)->execute();
        return $flag;
    }

    static function save($data, $table, \yii\db\Connection $db = null)
    {
        $fields = "(`" . implode("`,`", array_keys($data)) . "`)";
        $values = "('" . implode("','", $data) . "')";
        $sql = "insert into {$table} {$fields} VALUES {$values}";
        return static::insert($sql, $db);
    }

    static function multisave($data, $table, $db = null)
    {
        $fields = [];
        $values = [];
        foreach ($data as $_data) {
            if (!$fields) {
                $fields = "(`" . implode("`,`", array_keys($_data)) . "`)";
            }
            $values[] = "('" . implode("','", $_data) . "')";
        }
        $value_str = implode(",", $values);
        $sql = "insert into {$table} {$fields} VALUES {$value_str}";
        return static::insert($sql, $db);
    }

    static function insert($sql, \yii\db\Connection $db = null)
    {
        $db = $db ? $db : \Yii::$app->db;
        $transaction = $db->beginTransaction();
        $id = 0;
        try {
            $flag = $db->createCommand($sql)->execute();
            if ($flag === false) {
                $id = 0;
                $transaction->rollBack();
            } else {
                $id = $db->getLastInsertID();
                $transaction->commit();
            }
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }

        return $id;
    }

}